import React from 'react'
import { connect } from 'react-redux'
import { Form, Modal, Button, message, Row, Col, Select, Radio, Input, Icon, AutoComplete} from 'antd';
import menuRoute from 'routes/menuRoute'
import AddressPicker from 'containers/financial-management/wait-for-billing/new-billing/address-picker'
import 'styles/setting/wait-for-billing/wait-for-billing.scss'
import BillingService from 'containers/financial-management/wait-for-billing/wait-for-billing.service'
import 'styles/setting/wait-for-billing/new-rule.scss'
import {messages} from "share/common";
const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;


class NewBillingRule extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showAdressPicker:false,
      companyId:'',
      radioValue:'ALL',
      dayOptions:[],
      invoiceTitle:[],
      showInvoice: [],
      defaultAddressInfo:{},
      sectionMatch: {
        companyName: "-"
      },
      ruleTypeOptions: [],
      ruleData:{},
      billingType: JSON.stringify(props.billingType) !== "{}" ? props.billingType : props.params.billingType,
      dataSource: [],
      saveLoading: false,
      taxpayerNumber: null
    };
  }

  componentDidMount(){
    this.getDayOptions();
    this.getInvoiceTitle();
  }

  //获取供应商发票类型
  getVendorInvoiceType() {
    const { billingType, taxpayerNumber } = this.state;
    BillingService.getVendorInvoiceType(billingType, taxpayerNumber).then(res => {
      if (res.data && res.data.length > 0) {
        if (res.data.filter(item => !this.switchReceiving(item.type)).length > 0) {
          this.getDefaultAddress();
        }
        this.setState({ruleTypeOptions: res.data});
      }
    })
  }

  //根据发票类型状态切换收件信息
  switchReceiving = (type) => {
    let email = ['ELECTRONICORDINARY'];
    if (type && ~email.indexOf(type)) {
      return true;
    }
    return false;
  };

  getDayOptions = () => {
    const {dayOptions} = this.state;
    for(let i=1;i<32;i++){
      dayOptions.push(i)
    }
    this.setState({dayOptions})
  };

  //获得抬头信息
  getInvoiceTitle = ()=>{
    let params = {
      companyOid:this.props.company.companyOID
    };
    BillingService.getInvoiceTitle(this.state.billingType,params).then(res =>{
      if(res.data){
        this.setState({ invoiceTitle: res.data, showInvoice: res.data })
      }
    })
  };

  //获得默认地址
  getDefaultAddress(){
    BillingService.getDefaultAddress().then(res =>{
      this.setState({defaultAddressInfo:res.data})
    })
  }

  onRadioChange = (e) => {
    this.setState({ radioValue: e.target.value })
  };

  AddressPickerCancel = ()=>{
    this.setState({showAdressPicker:false});
  };

  goBack = ()=>{
    this.context.router.push(menuRoute.getRouteItem('wait-for-billing-list').url.replace(':billingType', this.state.billingType))
  };

  showAdressPicker = ()=>{
    this.setState({showAdressPicker:true});
  };

  submitNewBillingRule = (e) =>{
    e.preventDefault();
    let {invoiceTitle, radioValue, ruleData, defaultAddressInfo, billingType} = this.state;
    const defaultInfo = JSON.stringify(this.props.searchBilling) !== "{}" ? this.props.searchBilling : this.props.location.state.params;
    if(defaultAddressInfo === null){
      message.error(messages('financial-management.key487'/*地址信息必填*/));
      return;
    }
    this.props.form.validateFieldsAndScroll((err,values) => {
      if(!err){
        if(radioValue !=='CUSTOM'){
          ruleData.startMonth = null;
          ruleData.startDay = null;
          ruleData.endMonth = null;
          ruleData.endDay = null;
        }
        ruleData.vendor = billingType;
        ruleData.tenantId = this.props.tenant.id;
        if (!defaultInfo.company) {
          defaultInfo.company = {};
        }
        ruleData.vendorAccountId = defaultInfo.company.vendorAccountId;
        ruleData.vendorAccountName = defaultInfo.company.vendorAccountName;
        ruleData.title = invoiceTitle.filter(item => item.id === Number(values.qualificationId))[0].invoice_title;//发票抬头
        ruleData.taxpayerNumber = invoiceTitle.filter(item => item.id === Number(values.qualificationId))[0].tax_registration_number;//发票抬头号
        ruleData.qualificationId = values.qualificationId;//开票Id
        ruleData.keyInvoiceName = values.ruleName;//规则名称
        defaultInfo.paymentType.paymentTypeKey && (ruleData.paymentType = Number(defaultInfo.paymentType.paymentTypeKey));//支付方式
        ruleData.isHaveCommercial = defaultInfo.isHaveCommercial;
        defaultInfo.isHaveCommercial && (ruleData.bankCardType = defaultInfo.commercialType.commercialTypeKey);//商务卡方式
        ruleData.invoiceApplyType = values.invoiceApplyType;//开票类型
        ruleData.receiptedPeriodState = radioValue === 'ALL' ? 'ALL' : radioValue;//开票周期
        if(!this.switchReceiving(values.invoiceApplyType) && (!defaultAddressInfo || !defaultAddressInfo.billingContactOID)){
          message.warn(messages('financial-management.key460'/*请选择收货地址*/));
          return;
        }
        if (this.switchReceiving(values.invoiceApplyType)) {
          ruleData.email = values.email;//email收件地址
        } else {
          ruleData.billingContactOID = defaultAddressInfo.billingContactOID //地址ID
          ruleData.addressDetail = defaultAddressInfo //地址详情
        }
        ruleData.expenseSearchEntityOIDs=  defaultInfo.expenseLegalEntity === undefined ? [] :defaultInfo.expenseLegalEntity.map(item => {return item.companyReceiptedOID});
        ruleData.expenseSearchDepartmentOIDs = defaultInfo.expenseDepartment === undefined ? [] :defaultInfo.expenseDepartment.map(item => {return item.value});
        ruleData.costCenterItemOIDs = defaultInfo.costCenter === undefined ? [] :defaultInfo.costCenter.map(item => {return item.costCenterItemOID});
        ruleData.recDateTypeEnum = defaultInfo.recDateTypeEnum;
        this.setState({saveLoading: true});
        BillingService.addSmartRule(ruleData).then(res =>{
          if(res.status === 200){
            message.success(messages('financial-management.key488'/*添加成功*/))
            this.setState({saveLoading: false});
            this.goBack()
          }
        }).catch(() => {
          this.setState({saveLoading: false});
          message.error(messages('financial-management.key489'/*添加失败*/))
        })
      }
    })
  };

  //确认选择完地址
  handleChooseAddress = (value) =>{
    let {defaultAddressInfo} = this.state;
    defaultAddressInfo.billingContactOID = value.billingContactOID;
    defaultAddressInfo.country = value.country;
    defaultAddressInfo.stateProvince = value.stateProvince;
    defaultAddressInfo.cityRegion = value.cityRegion;
    defaultAddressInfo.area = value.area;
    defaultAddressInfo.streetLine = value.streetLine;
    defaultAddressInfo.phone = value.phone;
    defaultAddressInfo.isDefault = value.isDefault;
    defaultAddressInfo.zipCode = value.zipCode;
    defaultAddressInfo.fullName = value.fullName;
    delete defaultAddressInfo.explicitAddress
    this.setState({defaultAddressInfo})
  };

  //自定义周期
  startMonthChange = (value) => {
    let {ruleData} = this.state;
    ruleData.startMonth = value
    this.setState({ruleData})
  };

  startDayChange = (value) => {
    let {ruleData} = this.state;
    ruleData.startDay = value;
    this.setState({ruleData})
  };

  endMonthChange = (value) => {
    let {ruleData} = this.state;
    ruleData.endMonth = value;
    this.setState({ruleData})
  };

  endDayChange = (value) => {
    let {ruleData} = this.state;
    ruleData.endDay = value;
    this.setState({ruleData})
  };

  handleNameChange = (e)=>{
    if(e.target.value.length>30){
      Modal.error({
        title:messages('financial-management.key490'/*温馨提示：*/),
        content:(
          <div>
            <p>{messages('financial-management.key491'/*规则名称最多不超过30个字符*/)}</p>
          </div>
        )
      })
    }
  };

  emailHandleChange = (value) => {
    this.setState({
      dataSource: !value || value.indexOf('@') >= 0 ? [] : [
        `${value}@${this.props.user.email && ~this.props.user.email.indexOf('@')?this.props.user.email.split('@')[1]:''}`,
        `${value}@163.com`,
        `${value}@126.com`,
        `${value}@qq.com`,
        `${value}@sina.com`,
      ],
    });
  };

  renderBillingType = () => {
    const { billingType } = this.state;
    let result = '';
    switch (billingType){
      case 'DIDI':
        result = messages('financial-management.key423'/*滴滴账户*/);
        break;
      case 'CLOUD_HELIOS_HOTEL':
        result = messages('financial-management.key548'/*甄选账号*/);
        break;
      case 'SHEN_ZHOU':
        result = messages('financial-management.key549'/*神州账户*/);
        break;
      default:
        result = '';
        break;
    }
    return result;
  };

  handleChangeInvoice = value => {
    const { invoiceTitle } = this.state;
    let temp = invoiceTitle.find(item => item.id.toString() === value) || {};
    this.setState({ taxpayerNumber: temp.tax_registration_number },() => {
      this.getVendorInvoiceType();
    });
  };

  handleSearch = value => {
    const { invoiceTitle } = this.state;
    let showInvoice = [];
    invoiceTitle.map(item => {
      item.invoice_title.indexOf(value) > -1 && (showInvoice.push(item));
    });
    this.setState({ showInvoice })
  };

  render(){
    const { ruleTypeOptions, radioValue, dayOptions, showInvoice, defaultAddressInfo, showAdressPicker, billingType,
      dataSource, saveLoading, taxpayerNumber } = this.state;
    const defaultInfo = JSON.stringify(this.props.searchBilling) !== "{}" ? this.props.searchBilling : this.props.location.state.params;
    const { getFieldDecorator } = this.props.form;
    const {user} = this.props;
    let invoiceApplyType = this.props.form.getFieldValue('invoiceApplyType');
    return (
      <div className='new-rule' style={{ width: '100%' }}>
        <Form>
          <Row gutter={20} align="top">
            <Col span={12}>
              <FormItem label={messages('financial-management.key462'/*规则名称*/)}>
                {getFieldDecorator("ruleName",{
                  rules: [{
                    required: true,
                    message: messages('financial-management.key492'/*请输入规则名称*/)
                  }],
                })(
                  <Input placeholder={messages('financial-management.key463'/*请填写规则名称*/)} onChange={this.handleNameChange}/>
                )}
              </FormItem>
            </Col>
            <Col span={12}>
              <FormItem label={messages('financial-management.key428'/*开票抬头*/)}>
                {getFieldDecorator("qualificationId",{
                  rules: [{
                    required: true,
                    message: messages('financial-management.key472'/*请选择抬头*/)
                  }],
                })(
                  <Select
                    placeholder={messages('financial-management.key472'/*请选择抬头*/)}
                    onChange={this.handleChangeInvoice}
                    showSearch
                    onSearch={this.handleSearch}
                  >
                    {showInvoice.map(item=><Option key={item.id}>{item.invoice_title}</Option>)}
                  </Select>
                )}
              </FormItem>
            </Col>
            {
              taxpayerNumber && (
                <Col span={12}>
                  <FormItem label={messages('financial-management.key433'/*开票类型*/)}>
                    {getFieldDecorator("invoiceApplyType",{
                      rules:[
                        {
                          required: true,
                        }
                      ],
                      initialValue: ruleTypeOptions.length > 0 ? ruleTypeOptions[0].type : undefined
                    })(
                      <Select>
                        {ruleTypeOptions.map(item=><Option value={item.type} key={item.type}>{item.name}</Option>)}
                      </Select>
                    )}
                  </FormItem>
                </Col>
              )
            }
            <Col span={12}>
              <FormItem label={messages('financial-management.key429'/*日期范围*/)}>
                {getFieldDecorator('developCircle')(
                  <div>
                  <RadioGroup value={radioValue} onChange={this.onRadioChange}>
                    <Radio value='ALL'>{messages('financial-management.key432'/*全部*/)}</Radio>
                    <Radio value='CURRENTMONTH'>{messages('financial-management.key464'/*当月*/)}</Radio>
                    <Radio value='CUSTOM'>{messages('financial-management.key465'/*自定义*/)}</Radio>
                  </RadioGroup>
                  </div>
                )}
              </FormItem>
            </Col>
            {
              radioValue === 'CUSTOM' && (
                <Col span={12}>
                  <FormItem label={messages('financial-management.key493'/*自定义周期*/)}>
                    {getFieldDecorator('developCircleCustom')(
                      <div>
                        <Select style={{ width: 120 ,marginRight:10}} onChange={this.startMonthChange}>
                          <Option value='101'>{messages('financial-management.key466'/*上月*/)}</Option>
                          <Option value='102'>{messages('financial-management.key464'/*当月*/)}</Option>
                        </Select>
                        <Select style={{ width: 120 ,marginRight:10}} onChange={this.startDayChange}>
                          {dayOptions.map(item =><Option key={item} value={item}>{item}</Option>)}
                        </Select>
                        <span>{messages('financial-management.key430')/*至*/}</span>
                        <Select style={{ width: 120 ,marginRight:10,marginLeft:10}} onChange={this.endMonthChange}>
                          <Option value='101'>{messages('financial-management.key466'/*上月*/)}</Option>
                          <Option value='102'>{messages('financial-management.key464'/*当月*/)}</Option>
                        </Select>
                        <Select style={{ width: 120 ,marginRight:10}} onChange={this.endDayChange}>
                          {dayOptions.map(item =><Option key={item} value={item}>{item}</Option>)}
                        </Select>
                      </div>
                    )}
                  </FormItem>
                </Col>
              )
            }
            { this.switchReceiving(invoiceApplyType) &&
            <Col span={12}>{''}</Col>}
            {this.switchReceiving(invoiceApplyType)  && <Col span={12}>
              <FormItem label={messages('financial-management.key473'/*收件邮箱*/)}>
                {getFieldDecorator("email", {
                  rules: [{
                    required: true,
                    type: 'email',
                    message: `${messages('common.please.enter')}${messages('financial-management.key474'/*正确的收件邮箱*/)}`
                  }],
                  initialValue: user.email
                })(
                  <AutoComplete
                    dataSource={dataSource}
                    style={{width: 310}}
                    onChange={this.emailHandleChange}
                    placeholder={messages('common.please.enter')}
                  />
                )}
              </FormItem>
            </Col>}
          </Row>
          {!this.switchReceiving(invoiceApplyType)  && (<div>
            <div className='receive-info-title'><span
              style={{color: 'red'}}>* </span>{messages('financial-management.key475'/*收件信息*/)}</div>
            <div className='receive-info-content'>
              {defaultAddressInfo.fullName}&nbsp;&nbsp;{defaultAddressInfo.phone}&nbsp;&nbsp;{defaultAddressInfo.country}{defaultAddressInfo.stateProvince}{defaultAddressInfo.cityRegion}{defaultAddressInfo.streetLine}
              {defaultAddressInfo && defaultAddressInfo.isDefault &&
              <div className='default-button'>{messages('financial-management.key476'/*默认地址*/)}</div>}
            </div>
            <div className='more-address'
                 onClick={this.showAdressPicker}>{messages('financial-management.key477'/*更多地址*/)}<Icon type="down-circle-o"/>
            </div>
          </div>)}
          <div className='other-info'>
            <div className='header-title'>{messages('financial-management.key494'/*请核对以下查询条件*/)}：</div>
            <Row align='middle'>
              <Col span={3}>{messages('financial-management.key481'/*基准日期*/)}：</Col>
              <Col span={20}>{defaultInfo.recDateTypeName}</Col>
            </Row>
            {billingType !='CLOUD_HELIOS_HOTEL' &&
              <Row align='middle'>
                <Col span={3}>{this.renderBillingType()}：</Col>
                <Col span={20}>{defaultInfo.company.vendorAccountName}</Col>
              </Row>}
            <Row align='middle'>
              <Col span={3}>{messages('financial-management.key467'/*支付方式*/)}：</Col>
              <Col span={20}>{defaultInfo.paymentType.paymentTypeName}</Col>
            </Row>
            <Row align='middle'>
              <Col span={3}>{messages('financial-management.key434'/*单据信息法人*/)}：</Col>
              <Col span={20}>{defaultInfo.expenseLegalEntity === undefined ? <span>{messages('financial-management.key432'/*全部*/)}</span> : defaultInfo.expenseLegalEntity.map(item => <span>{item.companyName}</span>)}</Col>
            </Row>
            <Row align='middle'>
              <Col span={3}>{messages('financial-management.key495'/*单据部门*/)}：</Col>
              <Col span={20}>{defaultInfo.expenseDepartment === undefined ? <span>{messages('financial-management.key432'/*全部*/)}</span> : defaultInfo.expenseDepartment.map(item => <span>{item.name}</span>)}</Col>
            </Row>
            <Row align='middle'>
              <Col span={3}>{messages('financial-management.key431'/*单据信息成本中心*/)}：</Col>
              <Col span={20}>{defaultInfo.costCenter === undefined ? <span>{messages('financial-management.key432'/*全部*/)}</span> : defaultInfo.costCenter.map(item=><span>{item.name}</span>)}</Col>
            </Row>
            {defaultInfo.isHaveCommercial &&
              <Row align='middle'>
                <Col span={3}>{messages('financial-management.key436'/*商务卡支付*/)}：</Col>
                <Col span={20}>{defaultInfo.commercialType.commercialTypeName}</Col>
              </Row>
            }
          </div>
          <div className='footer-button'>
            <Button type="primary" htmlType="submit" onClick={this.submitNewBillingRule} loading={saveLoading}>{messages('financial-management.key478'/*确定*/)}</Button>
            <Button style={{ marginLeft: 8 }} onClick={this.goBack}>{messages('financial-management.key401'/*取消*/)}</Button>
          </div>
        </Form>
        <AddressPicker visible={showAdressPicker} onCancel={this.AddressPickerCancel} moreAdress={ value =>this.handleChooseAddress(value)} flag={'new'}/>
      </div>
    )
  }

}

NewBillingRule.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user,
    searchBilling: state.billing.searchBilling,
    billingType: state.billing.billingType,
    tenant: state.login.tenant
  }
}
const WrapppedNewBillingRule = Form.create()(NewBillingRule)
export default connect(mapStateToProps)(WrapppedNewBillingRule);
